#include <iostream>
#include <string>
#include <windows.h>
#include <sstream>
#include <fstream>
#include <vector>



std::string AnsiToUtf8(const std::string& ansi_str) {
    if (ansi_str.empty()) {
        return "";
    }
    
    // 第一步：ANSI转Unicode
    int unicode_len = MultiByteToWideChar(CP_ACP, 0, ansi_str.c_str(), -1, NULL, 0);
    if (unicode_len == 0) {
        return "";
    }
    
    std::vector<wchar_t> unicode_buffer(unicode_len);
    MultiByteToWideChar(CP_ACP, 0, ansi_str.c_str(), -1, unicode_buffer.data(), unicode_len);
    
    // 第二步：Unicode转UTF-8
    int utf8_len = WideCharToMultiByte(CP_UTF8, 0, unicode_buffer.data(), -1, NULL, 0, NULL, NULL);
    if (utf8_len == 0) {
        return "";
    }
    
    std::vector<char> utf8_buffer(utf8_len);
    WideCharToMultiByte(CP_UTF8, 0, unicode_buffer.data(), -1, utf8_buffer.data(), utf8_len, NULL, NULL);
    
    return std::string(utf8_buffer.data());
}

//测试编码
void testUtf8(){

    SetConsoleOutputCP(CP_UTF8);
    std::wstring wstr_test = L"张三abc";
    std::string str_test = "你好abc";
    std::string str_buffer;
    std::cout << "wstr size:" << wstr_test.size() << std::endl;
    std::cout << "string size:" << str_test.size() << std::endl;
    std::getline(std::cin , str_buffer);
    std::cout << "strbuffer size:" << str_buffer.size() << std::endl;
}

//输入几个数据 并保存输出
void test1(const std::string &str_file_name){

    //设置控制台为utf8 代码编写也用utf8
     SetConsoleOutputCP(CP_UTF8);
     
    std::cout << GetConsoleOutputCP() << std::endl;

    int id;
    std::string name;
    float math,en,cn;

    std::cin >> id >> name >> math >> en >> cn;

    std::cout << "数学:" << math <<  std::endl;
    std::cout << "英语:" << en <<  std::endl;
    std::cout << "语文:" << cn <<  std::endl;

    //将数据保存至文件
    std::ofstream of(str_file_name,std::ios::out|std::ios::app);
    if (of.is_open()){

        of << id << "\t" << name << "\t" << math << "\t" << en << "\t" << cn << "\n";
        of.close();
    }
    else
        std::cout << "文件打开失败" << std::endl;
    
}


int main(int argc, const char** argv) {


    // test1("1.txt");
    testUtf8();

    return 0;
}
